package com.starhub.utils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DateUtil {
    public static final String f_y_Str = "yyyy";
    public static final String f_ym_Str = "yyyy-MM";
    public static final String f_ymd_Str = "yyyy-MM-dd";
    public static final String f_hms_Str = "HH:mm:ss";
    public static final String f_hm_Str = "HH:mm";
    public static final String f_ymdhms_Str = "yyyy-MM-dd HH:mm:ss";
    public static SimpleDateFormat f_y = new SimpleDateFormat("yyyy");
    public static SimpleDateFormat f_ym = new SimpleDateFormat("yyyy-MM");
    public static SimpleDateFormat f_ymd = new SimpleDateFormat("yyyy-MM-dd");
    public static SimpleDateFormat f_hms = new SimpleDateFormat("HH:mm:ss");
    public static SimpleDateFormat f_hm = new SimpleDateFormat("HH:mm");
    public static SimpleDateFormat f_ymdhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static List<String> fastDates = new ArrayList();

    public DateUtil() {
    }

    public static String getCurrentDateString() {
        Calendar calendar = Calendar.getInstance();
        return f_ymd.format(calendar.getTime());
    }

    public static String getCurrentTimeString() {
        Calendar calendar = Calendar.getInstance();
        return f_hms.format(calendar.getTime());
    }

    public static String getCurrentDateTimeString() {
        Calendar calendar = Calendar.getInstance();
        return f_ymdhms.format(calendar.getTime());
    }

    public static String getYesterDateStr() {
        return getCalcDateStr(-1);
    }

    public static String getTomorrowDateStr() {
        return getCalcDateStr(1);
    }

    public static String getCalcDateStr(int amount) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(5, amount);
        return f_ymd.format(calendar.getTime());
    }

    public static String formatDate(Date date, String format) {
        return new SimpleDateFormat(format).format(date);
    }

    public static String getTimestampString(Timestamp timestamp) {
        return f_ymdhms.format(timestamp);
    }

    public static String[] getDateRange(String compareType, String conditionValue, Integer conditionDiffValue) {
        String[] range = new String[2];

        try {
            String[] dates;
            String begin;
            StringBuilder temp;
            if (!fastDates.contains(conditionValue)) {
                dates = conditionValue.split("~");
                begin = dates[0];
                if (!begin.equals("*")) {
                    range[0] = begin;
                }

                String endDate = "";
                if (dates.length > 1) {
                    endDate = dates[1];
                    if (!endDate.equals("*")) {
                        temp = new StringBuilder(endDate);
                        if (!isFormatDate(endDate, "yyyy-MM-dd HH:mm:ss")) {
                            temp.append(" 23:59:59");
                        }

                        range[1] = temp.toString();
                    }
                }
            } else {
                Date date;
                if (!"today".equals(conditionValue)) {
                    GregorianCalendar gregorianCalendar;
                    StringBuilder beg;
                    if ("yesterday".equals(conditionValue)) {
                        gregorianCalendar = new GregorianCalendar();
                        gregorianCalendar.add(5, -1);
                        date = gregorianCalendar.getTime();
                        beg = new StringBuilder(f_ymd.format(date));
                        range[0] = beg.toString();
                        beg.append(" 23:59:59");
                        range[1] = beg.toString();
                    } else if ("tomorrow".equals(conditionValue)) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.add(5, 1);
                        temp = new StringBuilder(f_ymd.format(calendar.getTime()));
                        range[0] = temp.toString();
                        temp.append(" 23:59:59");
                        range[1] = temp.toString();
                    } else {
                        if ("current_month".equals(conditionValue)) {
                            date = new Date();
                            begin = f_ym.format(date);
                            beg = new StringBuilder(begin);
                            beg.append("-01");
                            range[0] = beg.toString();
                            gregorianCalendar = new GregorianCalendar();
                            gregorianCalendar.setTime(f_ym.parse(begin));
                            gregorianCalendar.add(2, 1);
                            gregorianCalendar.add(5, -1);
                            temp = new StringBuilder(f_ymd.format(gregorianCalendar.getTime()));
                            temp.append(" 23:59:59");
                            range[1] = temp.toString();
                        } else if ("last_month".equals(conditionValue)) {
                            gregorianCalendar = new GregorianCalendar();
                            gregorianCalendar.add(2, -1);
                            begin = f_ym.format(gregorianCalendar.getTime());
                            beg = new StringBuilder(begin);
                            beg.append("-01");
                            range[0] = beg.toString();
                            gregorianCalendar.setTime(f_ym.parse(begin));
                            gregorianCalendar.add(2, 1);
                            gregorianCalendar.add(5, -1);
                            temp = new StringBuilder(f_ymd.format(gregorianCalendar.getTime()));
                            temp.append(" 23:59:59");
                            range[1] = temp.toString();
                        } else if ("current_year".equals(conditionValue)) {
                            date = new Date();
                            begin = f_y.format(date);
                            beg = new StringBuilder(begin);
                            beg.append("-01-01");
                            range[0] = beg.toString();
                            gregorianCalendar = new GregorianCalendar();
                            gregorianCalendar.setTime(f_y.parse(begin));
                            gregorianCalendar.add(1, 1);
                            gregorianCalendar.add(5, -1);
                            temp = new StringBuilder(f_ymd.format(gregorianCalendar.getTime()));
                            temp.append(" 23:59:59");
                            range[1] = temp.toString();
                        } else if ("last_year".equals(conditionValue)) {
                            gregorianCalendar = new GregorianCalendar();
                            gregorianCalendar.add(1, -1);
                            begin = f_y.format(gregorianCalendar.getTime());
                            beg = new StringBuilder(begin);
                            beg.append("-01-01");
                            range[0] = beg.toString();
                            gregorianCalendar.setTime(f_y.parse(begin));
                            gregorianCalendar.add(1, 1);
                            gregorianCalendar.add(5, -1);
                            temp = new StringBuilder(f_ymd.format(gregorianCalendar.getTime()));
                            temp.append(" 23:59:59");
                            range[1] = temp.toString();
                        }
                    }
                } else {
                    dates = null;
                    if (conditionDiffValue != null && conditionDiffValue != 0) {
                        GregorianCalendar gregorianCalendar = new GregorianCalendar();
                        gregorianCalendar.add(5, conditionDiffValue);
                        date = gregorianCalendar.getTime();
                    } else {
                        date = new Date();
                    }

                    temp = new StringBuilder(f_ymd.format(date));
                    range[0] = temp.toString();
                    temp.append(" 23:59:59");
                    range[1] = temp.toString();
                }

                if ("lt".equals(compareType)) {
                    range[0] = null;
                }
            }
        } catch (Exception var9) {
            log.error("trans date err:{}.", var9);
        }

        return range;
    }

    public static Date changeDate(Date date, int amount) {
        GregorianCalendar gregorianCalendar = new GregorianCalendar();
        gregorianCalendar.setTime(date);
        gregorianCalendar.add(5, amount);
        return gregorianCalendar.getTime();
    }

    public static Date timeChange(String time, int type) {
        Date date = new Date();
        if (Util.isEmpty(time)) {
            return date;
        } else {
            try {
                switch(type) {
                case 1:
                    date = f_y.parse(time);
                    break;
                case 2:
                    date = f_ym.parse(time);
                    break;
                case 3:
                    date = f_ymd.parse(time);
                    break;
                case 4:
                    date = f_hms.parse(time);
                    break;
                case 5:
                    date = f_ymdhms.parse(time);
                }
            } catch (ParseException var4) {
                log.error("timeChange err:{}.", var4);
            }

            return date;
        }
    }

    public static Boolean isFormatDate(String date, String dateformat) {
        boolean flag = true;

        try {
            DateTimeFormatter dtf = (new DateTimeFormatterBuilder()).appendPattern(dateformat).parseDefaulting(ChronoField.MONTH_OF_YEAR, 1L).parseDefaulting(ChronoField.DAY_OF_MONTH, 1L).parseDefaulting(ChronoField.HOUR_OF_DAY, 0L).toFormatter();
            LocalDateTime.parse(date, dtf);
        } catch (Exception var4) {
            flag = false;
        }

        return flag;
    }

    public static Timestamp getCurrentTimestamp() {
        return new Timestamp((new Date()).getTime());
    }

    public static List<LocalDate> getDateIntersection(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
        List<LocalDate> intersection = new ArrayList();
        LocalDate start = start1.isAfter(start2) ? start1 : start2;
        LocalDate end = end1.isBefore(end2) ? end1 : end2;
        if (!start.isAfter(end)) {
            for(LocalDate date = start; !date.isAfter(end); date = date.plusDays(1L)) {
                intersection.add(date);
            }
        }

        return intersection;
    }

    public static Long getDurationFromDateTimeList(List<LocalDateTime> dateTimes) {
        if (Util.isEmpty(dateTimes)) {
            return 0L;
        } else {
            List<LocalDateTime> startTimes = new ArrayList();
            List<LocalDateTime> endTimes = new ArrayList();

            for(int i = 0; i < dateTimes.size(); i += 2) {
                LocalDateTime start = (LocalDateTime)dateTimes.get(i);
                LocalDateTime end = (LocalDateTime)dateTimes.get(i + 1);
                startTimes.add(start);
                endTimes.add(end);
            }

            List<LocalDateTime> mergedStartTimes = new ArrayList();
            List<LocalDateTime> mergedEndTimes = new ArrayList();
            List<LocalDateTime> sortedStartTimes = new ArrayList(startTimes);
            sortedStartTimes.sort(Comparator.naturalOrder());
            LocalDateTime currentStart = null;
            LocalDateTime currentEnd = null;
            Iterator var8 = sortedStartTimes.iterator();

            int i;
            LocalDateTime endTime;
            while(var8.hasNext()) {
                LocalDateTime startTime = (LocalDateTime)var8.next();
                i = startTimes.indexOf(startTime);
                endTime = (LocalDateTime)endTimes.get(i);
                if (currentStart == null) {
                    currentStart = startTime;
                    currentEnd = endTime;
                } else if (startTime.isBefore(currentEnd)) {
                    currentEnd = currentEnd.isBefore(endTime) ? endTime : currentEnd;
                } else {
                    mergedStartTimes.add(currentStart);
                    mergedEndTimes.add(currentEnd);
                    currentStart = startTime;
                    currentEnd = endTime;
                }
            }

            mergedStartTimes.add(currentStart);
            mergedEndTimes.add(currentEnd);
            long totalDuration = 0L;

            for(i = 0; i < mergedStartTimes.size(); ++i) {
                endTime = (LocalDateTime)mergedStartTimes.get(i);
                LocalDateTime end = (LocalDateTime)mergedEndTimes.get(i);
                totalDuration += (long)Math.ceil((double)Duration.between(endTime, end).getSeconds() / 60.0D);
            }

            return totalDuration;
        }
    }

    static {
        fastDates.add("today");
        fastDates.add("yesterday");
        fastDates.add("current_month");
        fastDates.add("last_month");
        fastDates.add("current_year");
        fastDates.add("last_year");
    }
}

